package com.hao.wms.filter;

import com.hao.wms.domain.Employee;
import com.hao.wms.mvc.BaseAction;
import com.hao.wms.util.PermissionUtil;
import com.hao.wms.util.RequiredPermission;
import com.hao.wms.util.UserContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import java.lang.reflect.Method;
import java.util.Set;

public class SecurityIntercepter extends AbstractInterceptor{
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        Employee current = UserContext.getUser();
        if(current!=null&&current.isAdmin()){
            return actionInvocation.invoke();
        }
        String methodName = actionInvocation.getProxy().getMethod();
        Method method = actionInvocation.getProxy().getAction().getClass().getDeclaredMethod(methodName);
        if(!method.isAnnotationPresent(RequiredPermission.class)){
            return actionInvocation.invoke();
        }
        String expression = PermissionUtil.createExpression(method);
        Set<String> premissions = UserContext.getPermission();
        if(premissions.contains(expression)){
            actionInvocation.invoke();
        }
        return BaseAction.NOPERMISSION;
    }
}
